package team.se.tms.controller.assignment;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import team.se.tms.annotation.CheckFormat;
import team.se.tms.annotation.SpecialCheck;
import team.se.tms.constant.DateFormatConstant;
import team.se.tms.constant.SessionConstant;
import team.se.tms.controller.BaseController;
import team.se.tms.dto.*;
import team.se.tms.enums.DateEnum;
import team.se.tms.enums.ResultEnum;
import team.se.tms.exception.FileStoreException;
import team.se.tms.exception.SelectException;
import team.se.tms.exception.ParamException;
import team.se.tms.enums.ResultEnum;
import team.se.tms.exception.FileStoreException;
import team.se.tms.exception.UpdateException;
import team.se.tms.factory.ModelFactory;
import team.se.tms.po.AssignmentInfo;
import team.se.tms.po.StudentInfo;
import team.se.tms.po.UserInfo;
import team.se.tms.service.AssignmentInfoService;
import team.se.tms.util.DateUtil;
import team.se.tms.util.Jurisdiction;
import team.se.tms.util.ResultUtil;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @create on 2018/12/24
 * @author argentum
 */
@Slf4j
@Controller
@RequestMapping("assignment")
public class AssignmentController  extends BaseController {
    @Autowired
    AssignmentInfoService assignmentInfoService;

    /***
     * 查看作业详情
     *
     * @param assignmentRelevantDataDetail 作业详情
     * @return 页面
     * @create on 2019/1/4 by winkyle
     */
    @RequestMapping("/view_assignment_details")
    @CheckFormat
    public ModelAndView viewAssignmentDetails(AssignmentRelevantDataDetail assignmentRelevantDataDetail) throws Exception {
        log.debug("viewAssignmentDetails{}",assignmentRelevantDataDetail.toString());
        ModelAndView modelAndView = getModelAndView();
        modelAndView.addObject("assignmentRelevantDataDetail",assignmentRelevantDataDetail);
        modelAndView.addObject("judgeDetail",assignmentInfoService.getJudgeDetail(assignmentRelevantDataDetail.getAssignmentId()));
        modelAndView.setViewName("teach_course/assignment_details");
        return modelAndView;
    }
    /**
     * 根据用户id与任务id获取作业详细信息
     *
     * @param taskId 任务id
     * @param page 分页
     * @return json字符串
     * @throws Exception 异常
     * @create on 2019/1/1 by winkyle
     */
    @RequestMapping("/search_assignment_relevant_data_details")
    @ResponseBody
    public Object searchAssignmentRelevantDataDetails(@SpecialCheck("Pk")String taskId, @SpecialCheck("Pk")String teachCourseId, Page page) throws Exception{
        List<AssignmentRelevantDataDetail> assignmentRelevantDataDetails = assignmentInfoService.listAssignmentRelevantDataDetails(((UserInfo) Jurisdiction.getSession().getAttribute(SessionConstant.USER)).getUserId(), taskId, teachCourseId, page);
        if(assignmentRelevantDataDetails!=null&&assignmentRelevantDataDetails.size()>0) {
            for (int i = 0; i < assignmentRelevantDataDetails.size(); i++) {
                if(assignmentRelevantDataDetails.get(i).getTaskStartTime()!=null&&assignmentRelevantDataDetails.get(i).getTaskEndTime()!=null) {
                    assignmentRelevantDataDetails.get(i).setDeadline(DateUtil.format(assignmentRelevantDataDetails.get(i).getTaskStartTime(), DateFormatConstant.TIME) + " ~ " + DateUtil.format(assignmentRelevantDataDetails.get(i).getTaskEndTime(), DateFormatConstant.TIME));
                }else {
                    assignmentRelevantDataDetails.get(i).setDeadline("数据异常");
                }
            }
        }
        return page.getDataTabelJson(assignmentRelevantDataDetails);
    }

    /**
     * @create on 2018/12/7 by argentum
     * @update on 2018/12/18 by argentum
     *
     * @param projectIds
     * @param type   0时下载最新，1时下载全部
     */
    @RequestMapping("showProjectAssignment")
    @ResponseBody
    public Object searchProjectAssignments(@RequestParam("projectIds")List<String> projectIds, int type) throws Exception{
        List<AssignmentFile> assignmentFiles = assignmentInfoService.listAssignmentInfos(projectIds,type);
        return ResultUtil.success("查询成功",assignmentFiles);
    }

    /**
     * 修改作业下载状态
     * @create on 2018/12/7 by argentum
     * @update on 2018/12/18 by argentum
     *
     * @param assignmentIds
     * @throws Exception
     */
    @RequestMapping("editAssignmentState")
    public Object editAssignmentLoadStates(@RequestParam("assignmentIds") List<String> assignmentIds) throws Exception{
        Boolean result = assignmentInfoService.modifyAssignmentLoadStates(assignmentIds);
        if(!result){
            throw new UpdateException();
        }
        return  ResultUtil.success("修改状态成功");
    }

    /**
     * @create on 2018/12/31 by argentum
     * @return
     */
    @RequestMapping("toSearchAssignment")
    public String toSearchAssignment(){
        return "assignment/assignment_list";
    }
    /**
     * 35查询当前授课下所有作业
     * @create on 2018/12/7 by argentum
     * @update on 2018/12/30 by argentum
     *
     * @param
     */
    @RequestMapping("showAllAssignment")
    @ResponseBody
    public Object searchAllAssignment(Page page,String teachCourseId) throws Exception{
        //String teachCourseId = "20181208232425OL";
        List<AssignmentRelevantDataDetail> assignmentRelevantDataDetails = assignmentInfoService.listAssignmentDetails(page,teachCourseId);
        return page.getDataTabelJson(assignmentRelevantDataDetails);
    }


    /**
     * 查询该项目的所有作业信息
     *
     * @param projectId 项目ID
     * @return result
     * @throws Exception 异常
     * @create on 2019/1/2 by sunddly
     */
    @RequestMapping("getProjectAssignments")
    @ResponseBody
    public String searchAssignmentFiles(Page page,String projectId) throws Exception{
        System.out.println("******^^^^^^^^^^^^^^^");
        List<AssignmentFile> assignmentFileList =assignmentInfoService.listAssignmentFiles(page,projectId);
        System.out.println("******^^^^^^^^^^^^^^^");
        System.out.println("8761^^^^^^^^^^^^^^^"+assignmentFileList);
        return page.getDataTabelJson(assignmentFileList, DateEnum.ACCURATE_TO_SECOND);
    }

    /**
     * 查询最新作业信息状态
     *
     * @param projectId 项目Id
     * @return result
     * @throws Exception 异常
     * @create on 2018/12/27 by sunddly
     */
    @RequestMapping("viewLatestAssignment")
    @ResponseBody
    public Object searchLatestAssignmentAppraiseState(String projectId, HttpSession session) throws Exception{
        AssignmentInfo assignmentInfo = assignmentInfoService.getLatestAssignmentAppraiseState(projectId);
        //System.out.println("1*****************"+assignmentInfo);
        session.setAttribute("assignmentInfo",assignmentInfo);
        if (assignmentInfo==null){
            return ResultUtil.error(2,"上传第一个作业");
        }else{
            if(assignmentInfo.getAssignmentState()==0){
                return ResultUtil.error(0,"作业暂未批阅，是否重新上传");
            }else if (assignmentInfo.getAssignmentState()==1){
                return ResultUtil.error(1,"作业正在批阅，暂不能上传");
            }else if (assignmentInfo.getAssignmentState()==2){
                return ResultUtil.error(2,"作业已批改，是否上传下一个版本");
            }
        }
        throw new SelectException();
    }
    /**
     * 去上传流程作业界面
     *
     * @author sundlly
     * @date 2018/12/28
     */
    @RequestMapping("toUpload")
    public String toUploadMyAssignment(int type,HttpSession session){
        session.setAttribute("type",type);
        return "assignment/upload_flow_assignment";
    }

    /**
     * 上传流程作业
     *
     * @param session
     * @param multipartFile 文件
     * @return result
     * @throws Exception 异常
     * @create on 2018/12/27 by sunddly
     */
    @RequestMapping("uploadMyAssignment")
    @ResponseBody
    public Object uploadFlowAssignment(@RequestParam("file")MultipartFile multipartFile, HttpSession session) throws Exception{
        int version =0;
        String userId = ((UserInfo) Jurisdiction.getSession().getAttribute(SessionConstant.USER)).getUserId();
        AssignmentInfo assignmentInfo = new AssignmentInfo();
        AssignmentInfo oldAssignmentInfo = (AssignmentInfo) session.getAttribute("assignmentInfo");
        AssignmentInfo newAssignmentInfo = new AssignmentInfo();
        int type = (int)session.getAttribute("type");
        ProjectBasicDetail projectBasicDetail =(ProjectBasicDetail) session.getAttribute("projectBasicDetail");
        //System.out.println("****((((((((((((((((((("+projectBasicDetail);
        //获取暂未通过的第一个的阶段Id
        String stageId = null;
        for (int i=0;i<projectBasicDetail.getProjectStageDetail().getStageCompleteDetailList().size();i++){
            //System.out.println("****((((((((((((((((((("+projectBasicDetail.getProjectStageDetail().getStageCompleteDetailList().get(i).getStageComplete());
            //projectBasicDetail.getProjectStageDetail().getStageCompleteDetailList().get(i).setStageComplete(false);
            if(projectBasicDetail.getProjectStageDetail().getStageCompleteDetailList().get(i).getStageComplete()==false){
                stageId = projectBasicDetail.getProjectStageDetail().getStageCompleteDetailList().get(i).getStageId();
                break;
            }
        }
        //若获取最新的作业信息为空，设置作业信息的值
        if (type==1){
            assignmentInfo.setProjectId(projectBasicDetail.getProjectInfo().getProjectId());
            assignmentInfo.setTeaId(projectBasicDetail.getProjectInfo().getTeaId());
            assignmentInfo.setStageId(stageId);
            //此时版本(若是重新上传并上传的阶段和最新作业阶段一样，版本号递增)
            assignmentInfo.setAssignmentVersion(1);
            if(oldAssignmentInfo!=null){
                if(oldAssignmentInfo.getStageId().equals(stageId)){
                    version = oldAssignmentInfo.getAssignmentVersion()+1;
                    assignmentInfo.setAssignmentVersion(version);
                }
            }
//            else{
//                assignmentInfo.setAssignmentVersion(1);
//            }
            //assignmentInfo.setStuId("");
        }else if (type==0){
            assignmentInfo = oldAssignmentInfo;
        }
        Boolean uploadSuccess = assignmentInfoService.saveFlowAssignment(assignmentInfo,multipartFile,type);
        if(uploadSuccess){
            // System.out.println("2*****************");
            return ResultUtil.success("上传流程作业成功");
        }else{
            //System.out.println("3*****************");
            throw new FileStoreException(ResultEnum.UPLOAD_ERROR);
            //return ResultUtil.success("上传流程作业失败，请重新上传");
        }
    }


    /**
     * 方法描述
     *
     * @param assignmentId 作业Id
     * @param teaId 教师Id
     * @return ModelAndView
     * @throws Exception 异常
     * @create on 2019/1/3 by sunddly
     */
    @RequestMapping("viewFlowAssignment")
    public ModelAndView viewMyAssigmentDetail(String assignmentId,String teaId,HttpSession session) throws Exception{
        JudgeDetail judgeDetail = new JudgeDetail();
        AssignmentFile assignmentFile = new AssignmentFile();
        List<StudentInfo> studentInfos = new ArrayList<StudentInfo>();
        ModelAndView mv = new ModelAndView();
        ProjectBasicDetail projectBasicDetail =(ProjectBasicDetail) session.getAttribute("projectBasicDetail");
        System.out.println("$$$$$$$$$$$assignmentId"+assignmentId);
        judgeDetail = assignmentInfoService.getJudgeDetailInfo(assignmentId,teaId);
        judgeDetail.setProjectName(projectBasicDetail.getProjectInfo().getProjectName());
        studentInfos = projectBasicDetail.getStudentInfos();
        if (projectBasicDetail!=null){
            for (int i=0;i<projectBasicDetail.getAssignmentFiles().size();i++){
                System.out.println("1$$$$$$$$$$$getAssignmentId()"+projectBasicDetail.getAssignmentFiles().get(i));
                if(assignmentId.equals(projectBasicDetail.getAssignmentFiles().get(i).getAssignmentId())){
                    System.out.println("$$$$$$$$$$$projectBasicDetail.getAssignmentFiles().get(i).getAssignmentId()"+projectBasicDetail.getAssignmentFiles().get(i).getAssignmentId());
                    assignmentFile = projectBasicDetail.getAssignmentFiles().get(i);
                    break;
                }
            }
        }
        System.out.println("1U&&&&&&&&&&assignmentFile"+assignmentFile);
        System.out.println("1U&&&&&&&&&&assignmentFile");
        mv.addObject("assignmentFile",assignmentFile);
        mv.addObject("judgeDetail",judgeDetail);
        mv.addObject("studentInfos",studentInfos);
        mv.setViewName("assignment/my_flow_assignment_detail");
        return mv;
    }
    /**
     * 查询作业信息
     *
     * @param assignmentId 作业Id
     * @return AssignmentFile 解析后的作业
     * @throws Exception 异常
     * @create on 2018/12/27 by sunddly
     */
    @RequestMapping("downloadFlowAssignment")
    @ResponseBody
    public Object searchAssignment(String assignmentId) throws Exception{
        //assignmentId="20190101134713wC";
        AssignmentFile assignmentFile= assignmentInfoService.getAssignmentFile(assignmentId);
        System.out.println("%%%%%%%%%%%%%assignmentFile"+assignmentFile);
        return assignmentFile;
    }


    /**
     * 上传任务作业
     * @create on 2018/12/29 by argentum
     *
     * @param
     * @param multipartFile
     * @return
     * @throws Exception
     */
    @RequestMapping("uploadTaskAssignment")
    @ResponseBody
    public Object uploadTaskAssignment(String assignmentId,String teachCourseId,String projectId, String taskId, String stageId,
                                       int taskType, @RequestParam("file") MultipartFile multipartFile) throws Exception{
        if(multipartFile==null){
            throw new ParamException("文件不能为空");
        }
        UserInfo userInfo = (UserInfo) Jurisdiction.getSession().getAttribute(SessionConstant.USER);
        String userId = userInfo.getUserId();
        log.debug("上传了{},类型{}", multipartFile.getOriginalFilename(),multipartFile.getContentType());
        AssignmentInfo assignmentInfo = new AssignmentInfo();
        if(!assignmentId.equals("") && assignmentId!=null){
            assignmentInfo.setAssignmentId(assignmentId);
            log.debug("====================本次操作为新上传作业");
        }else{
            log.debug("====================本次操作为修改上传作业");
        }
        assignmentInfo.setProjectId(projectId);
        assignmentInfo.setStageId(stageId);
        assignmentInfo.setTaskId(taskId);
        assignmentInfo.setTaskType(taskType);
        Boolean success = assignmentInfoService.saveTaskAssignmentInfo(userId,teachCourseId, assignmentInfo,multipartFile);
        if(!success){
            throw new Exception("上传失败");
        }
        return ResultUtil.success("上传成功");
    }

    /**
     * 查看任务作业详情
     * @create on 2018/12/29 by argentum
     *
     * @param assignmentDetail
     * @return
     * @throws Exception
     */
    @RequestMapping("showAssignmentDetail")
    @ResponseBody
    public Object viewTaskAssignment(AssignmentRelevantDataDetail assignmentDetail) throws Exception{
        ModelAndView mv = new ModelAndView();
        JudgeDetail judgeDetail = assignmentInfoService.getJudgeDetail(assignmentDetail.getAssignmentId());
        mv.addObject("judgeDetail",judgeDetail);
        mv.setViewName("assignment/assignment_detail");
        //return mv;
        return judgeDetail;
    }

}
